#ifndef HTTP_RESPONSE_H
#define HTTP_RESPONSE_H

#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <string>
#include <unordered_map>

#include "../log/logger.h"


class HttpResponse {
public:
    HttpResponse();
    ~HttpResponse();

    void init_write_buffer(uint64_t write_buf_size);
    void init(const string &src_dir, const string &path, bool keepalive, int code = -1);
    void reset();

    bool make_response(struct iovec *iov, int *iov_cnt, uint64_t *bytes_to_send);

    void unmap_file();
    char *get_file_addr() {return m_file_addr;}


public:
    char *m_write_buffer{};
    uint64_t m_write_buf_size{};
    uint64_t m_write_idx{};

private:
    bool write_to_buffer(const std::string &msg);
    bool add_status_line();
    bool add_headers();
    bool add_content();
    bool add_error_body(const std::string &msg);
    void process_iov(struct iovec *iov, int *iov_cnt, uint64_t *bytes_to_send);
    std::string get_filetype();

private:
    int m_stat_code;
    std::string m_src_dir;
    std::string m_req_path;
    char *m_file_addr;
    struct stat m_file_stat{};

    bool m_is_keepalive;

    static const std::unordered_map<int, std::string> CODE_STATUS_TITLE;
    static const std::unordered_map<int, std::string> ERROR_STATUS_TEXT;
    static const std::unordered_map<std::string, std::string> FILETYPE_REF;
};


#endif //HTTP_RESPONSE_H
